package main.fileiterators;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;

import javax.swing.JFileChooser;
import javax.swing.UIManager;

import data.Saver;

public class IniFileIterator {


	static SaverPerformer performer = null;

	public static void main(String[] args){
		try{
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		}catch(Exception e){
			e.printStackTrace();
		}

		int runType = 1;

		if (runType == 1){
			performer = new ImprovementCounter();
		} else if (runType == 2){

		} else if (runType == 3){

		}

		JFileChooser fc = new JFileChooser();
		fc.setCurrentDirectory(new File(System.getProperty("user.dir")));
		fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
		int pick = fc.showOpenDialog(null);
		File f = fc.getSelectedFile();
		if (pick == JFileChooser.APPROVE_OPTION && f.isDirectory()){
			File[] content = f.listFiles();
			for (int i=0; i < content.length; i++){
				if (content[i].isFile()) {
				} else if (content[i].isDirectory()){
					File[] dirContent = content[i].listFiles();
					for (int j=0; j < dirContent.length; j++){
						ComputeFile(dirContent[j]);
					}
				}
				ComputeFile(content[i]);
			}
		} else {
			System.out.println("No directory chosen, Exiting");
		}
		logger.close();

		System.out.println(performer.printResults());

	}

	private static void ComputeFile(File f){
		System.out.println("Computing file - " + f.getAbsolutePath());
		if (f.isDirectory()) return;
		String tmpname = f.getAbsolutePath();
		String extension = tmpname.substring(tmpname.lastIndexOf('.'));
		String filename = tmpname.substring(0, tmpname.lastIndexOf('.'));
		if (extension.equalsIgnoreCase(".ini")){
			try{
				Saver s = new Saver(filename);
				if (s.getFileContent().size()>0){
					performer.doWithSaver(s);
				}
			}catch (Exception e) {
				log("Exception when trying to parse file - " + tmpname);
				log("Message was: " + e.getMessage());
				log("");
			}
		}
	}

	static{
		File f = new File("log.txt");
		f.delete();

		try {
			f.createNewFile();
			logger = new PrintWriter(f);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	static PrintWriter logger;

	private static void log(String line){
		logger.println(line);
	}
}
